# -*- coding:utf-8 -*-
# 检测 服务器上 是否有安装 ipas 包 和 安装包 下载帐号是否存在
import ctypes
import threading
import MySQLdb
import os
import socket
import json
import httplib
import urllib2
import uuid
import zipfile
import base64
import sys
import hashlib
import datetime
import time
import subprocess
import xml.dom.minidom

db_host   = "192.168.11.6"
db_user   = 'xyzs'
db_passwd = 'ikF5NNeJg2G8'
db_port   = 3309
db_name   = "app_xyapplist"

def commom_log(filename, content , write_type='wb'):
    try:
        f = open(filename , write_type)
        f.write(content);
        f.close()
    except:
        print('happen an exception when write file')
        return ""

def getInfoPlist(random_filename):
    try:
        zf       = zipfile.ZipFile(random_filename, "r")
        nList    = zf.namelist()
        type_val = 0
        BundleId = ''
        CFBundleShortVersionString = ''
        CFBundleVersion = ''
        for f in nList:
            if f.rfind('Info.plist') != -1:
                f_arr = f.split("/")
                if len(f_arr) == 3:
                    if(f_arr[2] == 'Info.plist'):
                        info     = zf.read(f)
                        plist    = readPlistFromString(info)
                        BundleId = plist['CFBundleIdentifier']

                        if plist.has_key('CFBundleShortVersionString'):
                            CFBundleShortVersionString = plist['CFBundleShortVersionString']
                        else:
                            CFBundleShortVersionString = ''
                        if plist.has_key('CFBundleVersion'):
                            CFBundleVersion = plist['CFBundleVersion']
                        else:
                            CFBundleVersion = ''

                        print CFBundleVersion

        return BundleId,CFBundleShortVersionString,CFBundleVersion
    except:
        return '','',''

def get_version(random_filename):
    try:
        zf = zipfile.ZipFile(random_filename, "a")
        zf.getinfo("iTunesMetadata.plist")
        data = zf.read("iTunesMetadata.plist")
        if data :

            index   = data.rfind('account hash')
            if index != -1:
                index_right = data.find('</string>', index)
                account_hash = data[index: index_right]
                account_hash = account_hash.replace("account hash</key>" , '').replace("<string>", "").strip()
            else:
                account_hash = ''

            index   = data.rfind('bundleShortVersionString')
            if index != -1:
                index_right = data.find('</string>', index)
                version = data[index: index_right]
                version = version.replace("bundleShortVersionString</key>" , '').replace("<string>", "").strip()
            else:
                version = ''
            index   = data.rfind('bundleVersion')
            if index != -1:
                index_right = data.find('</string>', index)
                bundleVersion = data[index: index_right]
                bundleVersion = bundleVersion.replace("bundleVersion</key>" , '').replace("<string>", "").strip()
            else:
                bundleVersion = ''
            return  version,bundleVersion,account_hash
        else:
            return '','',''
    except:
        return '','',''

arr  = '0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f'
arr  = arr.split(",")
conn = MySQLdb.connect(host=db_host,user=db_user,passwd=db_passwd,port=db_port,init_command="set names utf8")
conn.select_db(db_name)
cur  = conn.cursor()
is_genuine = 0
for x in arr:
    for xx in arr :
        tb_name = 'app_xyapplist_'+str(x)+".t_xyapplist_"+x+xx
        # sql  = "select itunesid , version , is_install , bundleVersion , useraccount from "+tb_name + " where useraccount = 'fuliaobei64577@163.com'";
        sql  = "select itunesid , version , is_install , bundleVersion , useraccount from "+tb_name + " where useraccount = 'chizuoying636593@163.com'";
        print sql
        cur.execute(sql)
        result = cur.fetchall()
        for f in result:
            itunesid      = f[0]
            version       = f[1]
            is_install    = f[2]
            bundleVersion = f[3]
            useraccount   = f[4]

            print itunesid

            m = hashlib.md5(str(itunesid))
            m.digest()
            md5  = m.hexdigest()
            str1 = md5[0: 2]
            str2 = md5[2: 4]

            useraccount_m = hashlib.md5(str(useraccount))
            useraccount_m.digest()
            useraccount_md5 = useraccount_m.hexdigest()


            random_filename = '/data/app/ipas/'+ str1 + "/" + str2 + "/" + str(md5) + str2 + str1 + '.ipa'
            print random_filename
            if os.path.exists(random_filename):
                return_value = get_version(random_filename)
                if return_value != '':
                    # if is_install == 0:
                    update_sql  = "update "+tb_name+" set is_install=1 , version='"+str(return_value[0])+"',bundleVersion='"+str(return_value[1])+"',is_hot = 1,is_genuine=1 where itunesid = '"+str(itunesid)+"' limit 1;";
                    if useraccount_md5 == return_value[2]:
                        if is_install == 0:
                            print update_sql+"\n"
                            commom_log('update_sql_success_account.log' , update_sql + "==db:=" + useraccount + '==' + useraccount_md5 + "==ipas==" + return_value[2] + "---" + random_filename + "\n" , 'a')
                            cur.execute(update_sql)
                    else:
                        print update_sql+"\n"
                        commom_log('update_sql_error_account.log' , update_sql + "==db:=" + useraccount + '==' + useraccount_md5 + "==ipas==" + return_value[2] + "---" + random_filename + "\n" , 'a')

cur.close()
conn.close()
